package com.tool.app.utils;

import org.dom4j.*;

import java.util.*;

/**
 * xml解析工具
 */
public class Dom4jUtils {
	//表示在整个文档中查找匹配的节点
	private static final String slash = "//";

	public static List<Map<String, Object>> xmlToList(String str, String xpathExpression) throws DocumentException {
		List<Map<String, Object>> result = new ArrayList<>();
		if (str == null) {
			return result;
		}
		Document doc = DocumentHelper.parseText(str);
		List<Node> nodes = doc.selectNodes(slash + xpathExpression);
		for (Node node : nodes) {
			if (node instanceof Element) {
				Element element = (Element) node;
				if (!element.elements().isEmpty()) {
					result.add(dom2Map(element));
				} else {
					Map<String, Object> map = new HashMap<>();
					map.put(element.getName(), element.getText());
					result.add(map);
				}
			}
		}
		return result;
	}

	public static List<Map<String, Object>> xmlToList(String xmlStr) throws DocumentException {
		List<Map<String, Object>> listMap = new ArrayList<>();
		Document doc = DocumentHelper.parseText(xmlStr);
		Element rootElement = doc.getRootElement();
		Iterator<Element> iterator = rootElement.elementIterator();
		while (iterator.hasNext()) {
			Element e = iterator.next();
			List<Element> elements = e.elements();
			if (!elements.isEmpty()) {
				listMap.add(dom2Map(e));
			} else {
				HashMap<String, Object> map = new HashMap<>();
				map.put(e.getName(), e.getText());
				listMap.add(map);
			}
		}

		return listMap;
	}

	public static Map<String, Object> dom2Map(Element e) {
		Map<String, Object> map = new HashMap<>();
		List<Element> list = e.elements();
		for (Element iter : list) {
			List<Object> mapList;
			if (!iter.elements().isEmpty()) {
				Map<String, Object> m = dom2Map(iter);
				if (map.get(iter.getName()) != null) {
					Object obj = map.get(iter.getName());
					if (obj instanceof ArrayList) {
						mapList = (List) obj;
						mapList.add(m);
					} else {
						mapList = new ArrayList<>();
						mapList.add(obj);
						mapList.add(m);
					}
					map.put(iter.getName(), mapList);
				} else {
					map.put(iter.getName(), m);
				}
			} else {
				if (map.get(iter.getName()) != null) {
					Object obj = map.get(iter.getName());
					if (obj instanceof ArrayList) {
						mapList = (List) obj;
						mapList.add(iter.getText());
					} else {
						mapList = new ArrayList<>();
						mapList.add(obj);
						mapList.add(iter.getText());
					}
					map.put(iter.getName(), mapList);
				} else {
					map.put(iter.getName(), iter.getText());
				}
			}
		}
		return map;
	}


}